<template>
  <div>
    <el-upload
      class="single-uploader"
      :show-file-list="false"
      list-type="picture-card"
      :before-upload="handleBeforeUpload"
      :http-request="uploadFile"
      v-model="imgUrl"
    >
      <img v-if="imgUrl" :src="imgUrl" class="single-uploader__image" />
      <el-icon v-else class="single-uploader__icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { UploadRawFile, UploadRequestOptions } from 'element-plus'
import { uploadFileApi } from '@/api/file'
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
const imgUrl = useVModel(props, 'modelValue', emit)

const uploadFile = async (options: UploadRequestOptions): Promise<any> => {
  console.log(options)
  const { data: fileInfo } = await uploadFileApi(options.file)
  imgUrl.value = fileInfo.url
}

const handleBeforeUpload = (file: UploadRawFile) => {
  if (file.size > 2 * 1048 * 1048) {
    ElMessage.error('文件大小不能超过2M')
    return false
  }
  return true
}
</script>

<style scoped lang="scss">
.single-uploader {
  overflow: hidden;
  cursor: pointer;
  border: 1px var(--el-border-color) solid;
  border-radius: 6px;

  &:hover {
    border-color: var(--el-color-primary);
  }

  &__image {
    display: block;
    width: 178px;
    height: 178px;
  }

  &___icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>